// Fill out your copyright notice in the Description page of Project Settings.


#include "Component/SlowTime.h"
#include "GameFramework/Character.h"
#include "Camera/CameraComponent.h"
#include "Kismet/GameplayStatics.h"

USlowTime::USlowTime()
{
	PrimaryComponentTick.bCanEverTick = false;
	PPSettings = FPostProcessSettings();
	SlowMotionValue = 0.25f;
	LerpSpeed = 0.01f;
	CurrentValue = 1.f;
}

void USlowTime::BeginPlay()
{
	Super::BeginPlay();

}

void USlowTime::ActivateAbility()
{
	Character = Cast<ACharacter>(GetOwner());
	if (!IsSlowTimeActive) {
		IsSlowTimeActive = true;
		UCameraComponent* TempCamera = Cast<UCameraComponent>(Character->GetComponentByClass(UCameraComponent::StaticClass()));
		if (TempCamera) {
			TempCamera->PostProcessSettings = PPSettings;
		}
		if (Lerp) {
			CurrentValue = 1.f;
			FTimerDelegate RespawnDelegate = FTimerDelegate::CreateUObject(this, &USlowTime::LerpStart);
			GetWorld()->GetTimerManager().SetTimer(UniqueHandle, RespawnDelegate, LerpSpeed, false);
		}
		else {
			UGameplayStatics::SetGlobalTimeDilation(this, SlowMotionValue);
			UGameplayStatics::SetGlobalPitchModulation(this, SlowMotionValue, 0.f);
			if (!IncludePlayer) {
				Character->CustomTimeDilation = 1.f / SlowMotionValue;
			}
		}
	}
	else {
		DeactivateAbility();
	}

}

void USlowTime::DeactivateAbility()
{
	IsSlowTimeActive = false;
	UCameraComponent* TempCamera = Cast<UCameraComponent>(Character->GetComponentByClass(UCameraComponent::StaticClass()));
	if (TempCamera) {
		TempCamera->PostProcessSettings = FPostProcessSettings();
	}
	UGameplayStatics::SetGlobalTimeDilation(this, 1.f);
	UGameplayStatics::SetGlobalPitchModulation(this, 1.f, 0.f);
	Character->CustomTimeDilation = 1.f;
}

void USlowTime::LerpStart()
{
	CurrentValue -= LerpSpeed;
	if (CurrentValue <= SlowMotionValue) {
		GetWorld()->GetTimerManager().ClearTimer(UniqueHandle);
	}
	else {
		UGameplayStatics::SetGlobalTimeDilation(this, CurrentValue);
		UGameplayStatics::SetGlobalPitchModulation(this, CurrentValue, 0.f);
		if (!IncludePlayer) {
			Character->CustomTimeDilation = 1.f / CurrentValue;
		}
	}
}

